package com.typhoon.spring_jdbctemplate.listener;

import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;

/**
 * 人类
 * 
 * @author Typhoon
 *
 */
public class Person {
	private int weight;//kg
	
	public Person(int weight) {
		super();
		this.weight = weight;
	}
	//创建当前对象的事件监听管理器
	PropertyChangeSupport listeners = new PropertyChangeSupport(this);

	public int getWeight() {
		return weight;
	}

	/**
	 * 设置属性的时候触发监听器
	 * 
	 * @param weight
	 */
	public void setWeight(int weight) {
		this.firePropertyChange("weight", this.weight, weight);
		//this.weight = weight;//为了测试,只触发不实际修改
	}
	
	/**
	 * 监听管理器为当前对象添加监听
	 * 
	 * @param listener
	 */
	public void addPropertyChangeListener(PropertyChangeListener listener) {
		this.listeners.addPropertyChangeListener(listener);
	}
	
	/**
	 * 管理器当前对象的管理器
	 * 
	 * @param listener
	 */
	public void removePropertyChangeListener(PropertyChangeListener listener) {
		this.listeners.removePropertyChangeListener(listener);
	}
	
    /**
     * 触发监听器
     * 
     * @param event
     */
	public void firePropertyChange(String propertyName,Object oldValue, Object newValue) {
    	this.listeners.firePropertyChange(propertyName, oldValue, newValue);
    }
	
	//测试
	public static void main(String[] args) {
		Person p = new Person(65);
		//添加监听器
		p.addPropertyChangeListener(new PropertyChangeListener() {
			@Override
			public void propertyChange(PropertyChangeEvent event) {
				System.out.println("propertyName:" + event.getPropertyName() + ",\n oldeValue:" + event.getOldValue() + "\n newValue:" + event.getNewValue());
				if("weight".equals(event.getPropertyName())) {//
					int oldValue = (int) event.getOldValue();
					int newValue = (int) event.getNewValue();
					if(oldValue > newValue ) {//体重变轻
						System.out.println("请注意增加营养!");
					} else  if(oldValue < newValue) {//变重
						System.out.println("该减肥了,请加强锻炼!");
					} else if(oldValue == newValue)  {
						System.out.println("身材保持不错,加油!");
					}
				}
			}
		});
		
		p.setWeight(64);
		p.setWeight(65);
		p.setWeight(66);
	}
	
}
